const Vue = require('vue')
const express = require('express')
const fs = require('fs')
const { createBundleRenderer } = require('vue-server-renderer')
const setupDevServer = require('./build/setup-dev-server')
const server = express() 

server.use('/dist', express.static('./dist'))

const isProd = process.env.NODE_ENV === 'production'
let renderer
let onReady

if(isProd){
  //生产模式
  const serverBundle = require('./dist/vue-ssr-server-bundle.json')
  const template = fs.readFileSync('./index.template.html', 'utf-8')
  const clientManifest = require('./dist/vue-ssr-client-manifest.json')
  
  renderer = createBundleRenderer(serverBundle,{
    template,
    clientManifest 
  })
}else{
  //开发模式 --》监视打包构建---》重新生成renderer渲染器
  onReady = setupDevServer(server, (serverBundle, template, clientManifest) => {
    renderer = createBundleRenderer(serverBundle,{
      template,
      clientManifest 
    })
  })
}

const render = (req,res) => {
  renderer.renderToString({
    title: '拉钩教育123', 
    meta: `<meta charset="UTF-8">`
  }, (err, html) => {
    if(err) {
      res.status(500).end('Intervel Server Error')
    }  
    //设置编码方式
    res.setHeader('Content-Type', 'text/html; charset=utf8')
    res.end(html)
  })
}


server.get('/', isProd
  ? render
  : async (req, res) => {
    //等到renderer渲染器
    await onReady
    render()
  }
)

server.listen(3000, () =>{
  console.log('server running at port 3000')
})